const whiteList = ["/api/login", "/api/getCity", "/api/getVerification", "/api/agentLogin"]//白名单
module.exports = (options, app) => {
    return async function robotMiddleware(ctx, next) {
        //判断白名单中是否有
        if (whiteList.includes(ctx.path)) {
            await next()
        } else {
            let {
                cookie,
                tokenagent
            } = ctx.headers;
            let token = null;
            if (cookie) {
                token = cookie.split(";")[0].split("=")[1];
            }
            if (token || tokenagent) {
                //验证token
                try {
                    if (token) {
                        console.log(111);
                        const jwt = require("jsonwebtoken");
                        let user = jwt.verify(token, ctx.app.config.keys);
                        console.log(user);
                        if (user.identity === "访客" && ctx.path.slice(0, 8) !== "/api/get") {
                            ctx.status = 405;
                            ctx.body = {
                                message: "你没有权限",
                                code: 405,
                                success: false
                            }
                        } else {
                            await next()
                        }
                    }
                    if (tokenagent) {
                        const jwt = require("jsonwebtoken");
                        jwt.verify(tokenagent, ctx.app.config.keys);
                        await next()
                    }
                } catch (err) {
                    console.log(err);
                    ctx.status = 403;
                    ctx.body = {
                        message: "你没有权限",
                        code: 403
                    }
                }
            } else {
                ctx.status = 406;
                ctx.body = {
                    message: "请登录",
                    code: 406
                }
            }
        }
    }
};
